package main

import (
	"b_plus_tree/tree"
	"flag"
	"fmt"
	"log"
	"os"
	"runtime/pprof"
	"strconv"
)

var memprofile2 = flag.String("", "heap2.prof", "write memory profile to `file`")

func main() {
	myTree := new(tree.BPlusTree)
	myTree.Initialize()
	for i := 100; i <= 200; i++ {
		myTree.Insert(tree.Key(i), tree.Value(strconv.Itoa(i)+"_v"))
	}
	for i := 100; i > 0; i-- {
		myTree.Insert(tree.Key(i), tree.Value(strconv.Itoa(i)+"_v"))
	}

	for i := 0; i <= 100; i++ {
		remove := myTree.Remove(tree.Key(i))
		fmt.Printf("remove %d:%v\n", i, remove)
	}

	for i := 200; i > 110; i-- {
		remove := myTree.Remove(tree.Key(i))
		fmt.Printf("remove %d:%v\n", i, remove)
	}

	fmt.Println("----------------scan--------------")
	//遍历
	cur := myTree.Ptr
	for cur.LeafNode.Next != nil {
		fmt.Println(cur.LeafNode)
		cur = cur.LeafNode.Next
	}
	fmt.Println(cur.LeafNode)
	fmt.Println("----------------End--------------")

	////查找
	//for i := 1; i < 200; i++ {
	//	data, b := tree.FindData(tree.Key(i))
	//	fmt.Println(b)
	//	fmt.Println(data)
	//}
	//
	//for i := 50; i <= 100; i++ {
	//	remove := tree.Remove(tree.Key(i))
	//	fmt.Println(remove)
	//}
	//for i := 199; i > 100; i-- {
	//	remove := tree.Remove(tree.Key(i))
	//	fmt.Println(remove)
	//}
	//fmt.Println("--------removed-------")
	//cur = tree.Ptr
	//for cur.LeafNode.Next != nil {
	//	fmt.Println(cur.LeafNode)
	//	cur = cur.LeafNode.Next
	//}
	//fmt.Println(cur.LeafNode)
	//fmt.Println("----------------FIND--------------")

	if *memprofile2 != "" {
		f, err := os.Create(*memprofile2)
		defer f.Close()
		if err != nil {
			log.Fatal("could not create memory profile: ", err)
		}
		//runtime.GC() // get up-to-date statistics
		if err := pprof.Lookup("heap").WriteTo(f, 0); err != nil {
			log.Fatal("could not write memory profile: ", err)
		}
	}
}
